package com.lagou.servlet;

import com.lagou.entity.Student;
import com.lagou.service.ClassGradeService;
import com.lagou.service.ClassGradeServiceImpl;
import com.lagou.service.StudentService;
import com.lagou.service.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "ClassGradeDeleteServlet", urlPatterns = "/classGradeDeleteServlet")
public class ClassGradeDeleteServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码方式， 解决中文乱码问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");

        // 1、获取前台得到的ids数据内容
        String idStr = request.getQueryString();
        idStr = idStr.replace("id=","");
        String[] ids = idStr.split("&");
        // 2、通过Service层实现对应功能
        ClassGradeService classGradeService = new ClassGradeServiceImpl();
        // 为了保证删除班级之前，该班级内没有关联的学生，应该通过班级编号查询一下学生表
        StudentService studentService = new StudentServiceImpl();

        // 获取输出流
        PrintWriter writer = response.getWriter();
        //获取模块名
        String contextPath = this.getServletContext().getContextPath();
        //拼接请求路径
        String hrefPath = contextPath + "/classGradePageQueryServlet";
        //使用循环分别对每个班级编号继续查找
        for(String string: ids){
            Student student = studentService.studentFindByClassIDService(Integer.parseInt(string));
            if(null!=student){
                writer.print("<script>alert('删除班级失败，该班级仍有学生!'); location.href='"+hrefPath+"';</script>");
                return;
            }
        }
        int res = classGradeService.classGradeDeleteService(ids);
        // 3、通过输出流向前台页面展示处理结果，然后重新请求一次数据
        if(0 != res){
            writer.print("<script> alert('管理班级信息成功！'); location.href='"+ hrefPath +"';</script>");
        } else {
            writer.print("<script> alert('管理班级信息失败！'); location.href='"+ hrefPath +"';</script>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
